import { defineStore } from 'pinia'
import { getOpportunityList, getOpportunityDetail, createOpportunity, getOpportunityComments, getCommentReplies, deleteComment } from '@/api/share'
import { ElMessage } from 'element-plus'

export const useOpportunityStore = defineStore('opportunity', {
  state: () => ({
    // 机会列表
    opportunityList: [],
    // 当前查看的机会详情
    currentOpportunity: null,
    // 评论列表 - 使用Map结构存储每个机会的评论
    commentList: {},
    // 评论分页信息 - 使用Map结构存储每个机会的评论分页
    commentsPagination: {},
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filters: {
      category: '',
      tag: '',
      keyword: ''
    },
    // 最后更新时间 - 用于控制数据刷新频率
    lastFetchTime: 0,
    // 加载状态
    loading: false
  }),

  getters: {
    // 获取已筛选的机会列表
    filteredOpportunities: (state) => {
      let filtered = [...state.opportunityList]
      
      if (state.filters.category) {
        filtered = filtered.filter(item => item.category === state.filters.category)
      }
      
      if (state.filters.tag) {
        filtered = filtered.filter(item => item.tags && item.tags.includes(state.filters.tag))
      }
      
      if (state.filters.keyword) {
        const keyword = state.filters.keyword.toLowerCase()
        filtered = filtered.filter(item => 
          (item.title && item.title.toLowerCase().includes(keyword)) ||
          (item.content && item.content.toLowerCase().includes(keyword))
        )
      }
      
      return filtered
    },

    // 获取特定机会的评论列表
    getCommentsByOpportunityId: (state) => (opportunityId) => {
      return state.commentList[opportunityId] || []
    },
    
    // 获取特定机会的评论分页信息
    getCommentsPaginationByOpportunityId: (state) => (opportunityId) => {
      return state.commentsPagination[opportunityId] || { page: 1, pageSize: 10, total: 0 }
    },
    
    // 检查是否需要刷新数据 (5分钟刷新一次)
    shouldRefreshData: (state) => {
      const now = Date.now();
      return (now - state.lastFetchTime) > 5 * 60 * 1000;
    }
  },

  actions: {
    // 获取机会列表，增加智能刷新
    async fetchOpportunityList(params = {}, forceRefresh = false) {
      // 如果数据已存在且不需要强制刷新，直接返回缓存数据
      if (this.opportunityList.length > 0 && !forceRefresh && !this.shouldRefreshData) {
        return { list: this.opportunityList, total: this.pagination.total };
      }
      
      try {
        this.loading = true;
        const res = await getOpportunityList({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...this.filters,
          ...params
        });
        
        if (res.code === 200 && res.data) {
          this.opportunityList = res.data.list || [];
          this.pagination = {
            page: params.page || this.pagination.page,
            pageSize: params.pageSize || this.pagination.pageSize,
            total: res.data.total || 0
          };
          this.lastFetchTime = Date.now();
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('获取机会列表失败:', error);
        ElMessage.error('获取机会列表失败');
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 获取机会详情
    async fetchOpportunityDetail(id) {
      try {
        this.loading = true;
        const res = await getOpportunityDetail(id);
        
        if (res.code === 200 && res.data) {
          this.currentOpportunity = res.data;
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('获取机会详情失败:', error);
        ElMessage.error('获取机会详情失败');
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 获取评论列表
    async fetchCommentList(opportunityId, params = {}) {
      try {
        this.loading = true;
        // 确保commentsPagination对象存在
        if (!this.commentsPagination[opportunityId]) {
          this.commentsPagination[opportunityId] = {
            page: 1,
            pageSize: 10,
            total: 0
          };
        }
        
        // 准备请求参数
        const requestParams = {
          page: params.page || this.commentsPagination[opportunityId].page,
          pageSize: params.pageSize || this.commentsPagination[opportunityId].pageSize,
          ...params
        };
        
        const res = await getOpportunityComments(opportunityId, requestParams);
        
        if (res.code === 200 && res.data) {
          // 将评论列表保存到commentList
          this.commentList[opportunityId] = res.data.list || [];
          
          // 更新分页信息
          this.commentsPagination[opportunityId] = {
            page: requestParams.page,
            pageSize: requestParams.pageSize,
            total: res.data.total || 0
          };
          
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('获取评论列表失败:', error);
        ElMessage.error('获取评论列表失败');
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 获取评论回复列表
    async fetchCommentReplies(commentId, params = {}) {
      try {
        this.loading = true;
        
        const res = await getCommentReplies(commentId, params);
        
        if (res.code === 200 && res.data) {
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('获取评论回复失败:', error);
        ElMessage.error('获取评论回复失败');
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 创建机会
    async createOpportunity(opportunityData) {
      try {
        this.loading = true;
        const res = await createOpportunity(opportunityData);
        
        if (res.code === 200 && res.data) {
          // 更新列表，仅在成功时添加到列表前端
          this.opportunityList.unshift(res.data);
          ElMessage.success('发布机会成功');
          return res.data;
        }
        return null;
      } catch (error) {
        console.error('发布机会失败:', error);
        ElMessage.error('发布机会失败');
        return null;
      } finally {
        this.loading = false;
      }
    },

    // 删除评论
    async deleteComment(opportunityId, commentId) {
      try {
        this.loading = true;
        const res = await deleteComment(commentId);
        
        if (res.code === 200) {
          // 从评论列表中移除
          if (this.commentList[opportunityId]) {
            this.commentList[opportunityId] = this.commentList[opportunityId].filter(comment => comment.id !== commentId);
          }
          
          // 更新评论总数
          if (this.commentsPagination[opportunityId] && this.commentsPagination[opportunityId].total > 0) {
            this.commentsPagination[opportunityId].total -= 1;
          }
          
          ElMessage.success('删除评论成功');
          return true;
        }
        return false;
      } catch (error) {
        console.error('删除评论失败:', error);
        ElMessage.error('删除评论失败');
        return false;
      } finally {
        this.loading = false;
      }
    },

    // 更新筛选条件 - 优化为使用本地筛选而不是每次都请求API
    updateFilters(filters) {
      this.filters = { ...this.filters, ...filters };
      
      // 如果已有数据，先在前端进行筛选
      if (this.opportunityList.length > 0 && !this.shouldRefreshData) {
        // 不立即调用后端API，使用前端过滤
        return;
      }
      
      // 数据过期或没有数据时才请求API
      this.fetchOpportunityList({ page: 1 });
    },

    // 重置筛选条件
    resetFilters() {
      this.filters = {
        category: '',
        tag: '',
        keyword: ''
      };
      // 使用强制刷新获取最新数据
      this.fetchOpportunityList({ page: 1 }, true);
    },
    
    // 清理状态
    clearState() {
      this.opportunityList = [];
      this.currentOpportunity = null;
      this.commentList = {};
      this.commentsPagination = {};
      this.lastFetchTime = 0;
    }
  }
}); 